<template>
    <div class="login">
        <div class="background">
            <el-form ref="form" :rules="rules" :model="form">
                <p>系统登录</p>
                <el-form-item  prop="account">
                    <el-input prefix-icon="el-icon-user-solid" v-model="form.account"></el-input>
                </el-form-item>
                <el-form-item  prop="password">
                    <el-input prefix-icon="el-icon-lock" show-password v-model="form.password"></el-input>
                </el-form-item>
                <el-button type="primary" @click="submit">登录</el-button>
            </el-form>
        </div>
    </div>
</template>

<script>
// axios第三层：使用封装好的接口函数
import {checkLogin} from "@/api/user.js";  //引入（普通引入需要用｛｝解构）
// 引入local
import local from "@/utils/local.js";

export default {
    data() {
        return {
            form: {
                account: "",
                password: "",
            },

            // 表单验证规则
            rules: {
                account: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { min: 3, message: '长度在3位以上', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, message: '长度在6位以上', trigger: 'blur' }
                ],
            }    
        }
    },

    methods: {
            submit() {
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    // 验证通过，提交数据去登陆
                    let res = await checkLogin(this.form)
                    if(res.data.code === 0){
                        local.set("token", res.data.token);  //存储token
                        local.set("role", res.data.role);  //存储role
                        await this.$router.push("/index");  //成功后跳转页面
                        window.location.reload();  //刷新一次，重新加载路由
                    }
                } 
            });
        },
    }
}
</script>

<style lang="less" scoped>
.login{
    height: 100%;
    background:url(../../assets/images/logo.png) no-repeat center center;
    background-size: cover;

    .background{
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.4);

        // 表单
        .el-form{
            width: 300px;

            // 系统登录
            p{
                margin-bottom: 20px;
                text-align: center;
                color: #fff;
                font-size: 20px;
            }

            // 登录框
            button, [type="button"], [type="reset"], [type="submit"]{
                width: 100%;
            }
        }
    }
}
</style>